package com.huangmb.anymark.server.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 备注:
 *
 * @author hmb
 * @version 1.0
 * @since 2016/4/4 16:03
 */
public class DigestUtils {
    private final static Logger LOGGER = LoggerFactory.getLogger(DigestUtils.class.getSimpleName());
    private final static String HMACSHA1 = "HmacSHA1";
    private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
            'e', 'f'};

    private DigestUtils() {
        throw new AssertionError();
    }

    /**
     * MD5加密
     *
     * @param str 明文
     * @return String 密文
     */
    public static String md5(String str) {
        if (str == null) {
            return null;
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.update(str.getBytes());
            return new String(encodeHex(messageDigest.digest()));
        } catch (Exception e) {
            LOGGER.warn("md5 加密错误",e);
        }
        return null;
    }
    public static String sha1(String str){
        if(str == null){
            return null;
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
            messageDigest.update(str.getBytes());
            return new String(encodeHex(messageDigest.digest()));
        } catch (NoSuchAlgorithmException e) {
            LOGGER.warn("sha1 加密错误",e);
        }
        return null;
    }
    public static byte[] hmacSha1(String text,String key){
        try {
            byte[] keyBytes = key.getBytes("UTF-8");
            SecretKey secretKey = new SecretKeySpec(keyBytes, HMACSHA1);
            Mac mac = Mac.getInstance(HMACSHA1);
            mac.init(secretKey);
            return mac.doFinal(text.getBytes("UTF-8"));

        }catch (Exception e){
            LOGGER.warn("hmac-sha1 加密失败",e);
        }
        return null;
    }

    /**
     * Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order.
     * The returned array will be double the length of the passed array, as it takes two characters to represent any
     * given byte.
     *
     * @param data a byte[] to convert to Hex characters
     * @return A char[] containing hexadecimal characters
     */
    private static char[] encodeHex(final byte[] data) {
        final int l = data.length;
        final char[] out = new char[l << 1];
        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = DIGITS_LOWER[(0xF0 & data[i]) >>> 4];
            out[j++] = DIGITS_LOWER[0x0F & data[i]];
        }
        return out;
    }

}
